<template>
  <div class="mini-cart">
    <div class="mini-cart__overlay mini-cart__toggler"></div>
    <div class="mini-cart__content">
      <div class="mini-cart__top">
        <h3 class="mini-cart__title">购物车</h3>
        <span class="mini-cart__close mini-cart__toggler"
          ><i class="organik-icon-close"></i
        ></span>
      </div>
      <div class="mini-cart__item" :key="c.id" v-for="c in carts">
        <img :src="c.image" alt="" />
        <div class="mini-cart__item-content">
          <div class="mini-cart__item-top">
            <h3>
              <a :title="c.name" :href="'/product-details.html?id=' + c.id">{{
                c.name
              }}</a>
            </h3>
            <p>${{ c.price }}</p>
          </div>
          <div class="quantity-box">
            <button
              type="button"
              class="sub"
              @click="increaseCartNumber(c.id, -1)"
            >
              -
            </button>
            <input type="number" :value="c.num" />
            <button
              type="button"
              class="add"
              @click="increaseCartNumber(c.id, 1)"
            >
              +
            </button>
          </div>
        </div>
      </div>
      <a
        href="/cart.html"
        tppabs="https://www.17sucai.com/preview/776298/2021-05-10/oganik/checkout.html"
        class="thm-btn mini-cart__checkout"
        >显示更多</a
      >
    </div>
  </div>
</template>

<style scoped>
.mini-cart__content {
  padding: 30px 5px;
  overflow-y: hidden;
}
.mini-cart__item-content h3 a {
  word-break: break-all;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  width: 6em;
}
.mini-cart__container {
  height: calc(100% - 74px - 97px);
  padding-right: 15px;
  overflow-y: auto;
}
</style>

<script>
/* eslint-disable */
export default {
  name: "MiniCart",
  //使用props接收父组件的值
  props: ["goods"],
  data() {
    return {
      CKEY: "BANDEER_CITY_CART",
      carts: null,
    };
  },
  watch: {
    // 监控值的变化
    goods: {
      handler(n) {
        this.joinCart(n);
      },
      deep: true,
    },
  },
  mounted() {
    // console.log("mounted")
    this.getCartsArray();
  },
  methods: {
    //使用点击事件来触发，子组件像父组件传值
    //使用this.$emit（属性名，属性值）
    getCartsArray() {
      try {
        this.carts = JSON.parse(localStorage.getItem(this.CKEY));
      } catch (e) {
        console.log("error");
      }
      // 如果从 localStorage 中获取的不是数组, 则将其赋值为数组
      if (!Array.isArray(this.carts)) {
        this.carts = [];
      }
      // this.$emit("carts", this.carts);
      this.$emit("getCarts", this.carts);
    },

    /**
     * 加入购物车, 被用于首页的上新产品和商品列表页面
     */
    joinCart(goods) {
      console.log("minicart joinCart");
      if (!(goods.id && goods.name && goods.image && goods.price)) {
        return [];
      }
      // 2. 判断已经存储的数据中是否包含即将被加入到购物车中的商品
      let exists = false;
      console.log(this.carts);
      for (let i = 0; i < this.carts.length; i++) {
        if (this.carts[i].num && this.carts[i].id === goods.id) {
          exists = true;
          if (goods.num != undefined && goods.num != null) {
            this.carts[i] = goods;
          } else {
            // 如果在数组中存在，则在原来的基础上增加 1
            this.carts[i].num++;
          }

          break;
        }
      }
      // 3. 如果不存在，则 push 到数组中
      if (exists === false) {
        // 有数量
        if (goods.num != undefined && goods.num != null) {
          this.carts.push(goods);
        } else {
          goods.num = 1;
          this.carts.push(goods);
        }
      }
      // 4. 将数据重新存储到 localStorage
      localStorage.setItem(this.CKEY, JSON.stringify(this.carts));
      this.getCartsArray();
      /**
       * 从 localStorage 读取购物车的数据
       */
      // 打开右侧的迷你购物车
      {
        $(".mini-cart").toggleClass("expanded");
        $(".mobile-nav__wrapper").removeClass("expanded");
        $("body").toggleClass("locked");
      }
    },
    /**
     * 自增购物车中的商品的购买数量
     * @param id
     */
    increaseCartNumber(id, step) {
      for (let i = 0; i < this.carts.length; i++) {
        if (this.carts[i].num > 0 && this.carts[i].id === id) {
          // 将新的数字赋值到购物车数量中
          this.carts[i].num += step;
        }
        // 当num已经是0时,只能加
        if (this.carts[i].num == 0 && this.carts[i].id === id && step == 1) {
          // 将新的数字赋值到购物车数量中
          this.carts[i].num += step;
        }
      }
      localStorage.setItem(this.CKEY, JSON.stringify(this.carts));
    },
  },
};
</script>
